<template>
  <div class="login-page">
    <h1>用户登录</h1>
    <AuthForm
        button-text="登录"
        @submit="handleLogin"
    />
    <p v-if="error" class="error-message">{{ error }}</p>
    <p class="forgot-password">
      <router-link to="/reset-password">忘记密码？</router-link>
    </p>
    <p class="register-link">没有账号？<router-link to="/register">立即注册</router-link></p>
  </div>
</template>

<script>
import AuthForm from '@/components/AuthForm.vue'

export default {
  name: 'LoginPage',
  components: { AuthForm },
  data() {
    return {
      error: '',
      isLoading: false
    }
  },
  methods: {
    async handleLogin(formData) {
      // 清空之前的错误信息
      this.error = ''

      // 进行前端校验
      if (!formData.userName || !formData.password) {
        this.error = '请填写用户名和密码'
        return
      }

      if (formData.userName.length < 4) {
        this.error = '用户名至少包含4个字符'
        return
      }

      this.isLoading = true

      try {
        // 调用 Vuex 的登录 action
        const result = await this.$store.dispatch('auth/login', {
          userName: formData.userName,
          password: formData.password
        })

        // 登录成功，跳转到成功页面
        console.log('登录成功响应:', result)
        this.$router.push('/image-processing') // 这里根据实际需要跳转
      } catch (err) {
        // 错误处理
        console.error('登录失败详情:', err)

        this.error = err.message || '登录失败'
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

<style scoped>
.login-page {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
}

.error-message {
  color: #f56c6c;
  margin: 10px 0;
  font-size: 14px;
}

.register-link {
  margin-top: 20px;
  color: #666;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}

h1 {
  color: #333;
  margin-bottom: 24px;
}
</style>
